Radar Host Communication library  2020.08.13
COMPort_Unix.c
Go to the documentation of this file.
1 
10 /* ===========================================================================
11 ** Copyright (C) 2016-2020 Infineon Technologies AG
12 ** All rights reserved.
13 ** ===========================================================================
14 **
15 ** ===========================================================================
16 ** This document contains proprietary information of Infineon Technologies AG.
17 ** Passing on and copying of this document, and communication of its contents
18 ** is not permitted without Infineon's prior written authorisation.
19 ** ===========================================================================
20 */
21 
22 /*
23 ==============================================================================
24  1. INCLUDE FILES
25 ==============================================================================
26 */
27 #define _DEFAULT_SOURCE // for cfmakeraw
28 #include "COMPort.h"
29 
30 #if (defined __APPLE__) || (defined LINUX) || (defined __linux__)
31 #include <stdbool.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <sys/ioctl.h>
35 #include <fcntl.h>
36 #include <termios.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <time.h>
42 
43 /*
44 ==============================================================================
45  3. LOCAL TYPES
46 ==============================================================================
47 */
51 struct com_s
52 {
53  int handle;
54  uint32_t timeout_period_ms;
56 };
57 
58 /*
59 ==============================================================================
60  7. EXPORTED FUNCTIONS
61 ==============================================================================
62 */
63 
64 #if defined __APPLE__
65 uint32_t com_get_port_list(char* port_list, size_t buffer_size)
66 {
67  /*
68  * On Mac devices are represented as files in /dev, search for the Com
69  * ports (cu) that have a USB in its name
70  * Note: use cu* instead of tty* because tty blocks on open for carrier
71  * detection
72  */
73  const char dev_dir[] = "/dev";
74  const char search_pattern[] = "cu.usb";
75 
76  uint32_t num_available_ports = 0;
77  DIR* dir_handle;
78 
79  /* init port list to empty string */
80  if (buffer_size > 0)
81  {
82  port_list[0] = 0;
83  }
84 
85  /* open directory that contains the serial device files */
86  dir_handle = opendir(dev_dir);
87 
88  if (dir_handle != NULL)
89  {
90  /* read entry per entry */
91  struct dirent* dir_entry;
92 
93  while ((dir_entry = readdir(dir_handle)) != NULL)
94  {
95  size_t name_length;
96 
97  /* compare device file name with the search pattern */
98  char current_device[128];
99 
100  if (strstr(dir_entry->d_name, search_pattern) == NULL)
101  {
102  continue;
103  }
104 
105  /* add the port name to the list, if buffer capacity is
106  * sufficient
107  */
108  strcpy(current_device, dev_dir);
109  strcat(current_device, "/");
110  strcat(current_device, dir_entry->d_name);
111 
112  name_length = strlen(current_device);
113 
114  if (num_available_ports > 0)
115  {
116  /* add one for the separator */
117  ++name_length;
118  }
119 
120  if (name_length < buffer_size)
121  {
122  if (num_available_ports > 0)
123  {
124  strcat(port_list, ";");
125  }
126 
127  strcat(port_list, current_device);
128 
129  /* update ramaining capacity of string buffer */
130  buffer_size -= name_length;
131  }
132 
133  /* port is available, so increase counter */
134  ++num_available_ports;
135  }
136 
137  /* close directory stream */
138  closedir(dir_handle);
139  }
140 
141  return num_available_ports;
142 }
143 #else /* Linux */
144 /* check that file exists */
145 static bool file_exists(const char* path)
146 {
147  FILE* fh = fopen(path, "r");
148  if (fh == NULL)
149  return false;
150 
151  fclose(fh);
152  return true;
153 }
154 
155 /* check for PID and VID in uevent file */
156 static bool check_uevent(const char* path, const char* vid, const char* pid)
157 {
158  char buffer[2048];
159  bool ret = false;
160  long vid_ = strtol(vid, NULL, 16), pid_ = strtol(pid, NULL, 16);
161 
162  FILE* fh = fopen(path, "r");
163  if (fh == NULL)
164  return false;
165 
166  while (fgets(buffer, sizeof(buffer), fh))
167  {
168  char* p = NULL;
169  if (strncmp(buffer, "PRODUCT=", 8) != 0)
170  continue;
171 
172  /* PRODUCT=58b/58/1 */
173  char* s_vid = buffer + 8;
174  if ((p = strchr(s_vid, '/')) == NULL)
175  break;
176  *p = '\0';
177  char* s_pid = p + 1;
178 
179  if ((p = strchr(s_pid, '/')) == NULL)
180  break;
181  *p = '\0';
182 
183  if ((strtol(s_vid, NULL, 16) == vid_) && (strtol(s_pid, NULL, 16) == pid_))
184  {
185  ret = true;
186  break;
187  }
188  }
189 
190  fclose(fh);
191 
192  return ret;
193 }
194 
195 uint32_t com_get_port_list(char* port_list, size_t buffer_size)
196 {
197  uint32_t num_available_ports = 0;
198 
199  memset(port_list, 0, buffer_size);
200 
201  const char* sysdir = "/sys/class/tty/";
202  DIR* dir_handle = opendir(sysdir);
203  if (dir_handle == NULL)
204  return 0;
205 
206  struct dirent* dir_entry;
207  while ((dir_entry = readdir(dir_handle)) != NULL)
208  {
209  /* search for /sys/class/tty/ttyACMXXX where XXX is a number */
210  const char* fname = dir_entry->d_name;
211  if (strncmp(fname, "ttyACM", 6) != 0)
212  continue;
213 
214  /* check for correct vendor and product id in /sys/class/tty/ttyACMXXX/device/uevent */
215  char path[PATH_MAX] = { 0 };
216  snprintf(path, sizeof(path) - 1, "%s/%s/device/uevent", sysdir, fname);
217  if (check_uevent(path, IFX_RADAR_VID, IFX_RADAR_PID) || check_uevent(path, IFX_RADAR_VID, IFX_RADAR_FF_PID))
218  {
219  char port[512] = { 0 };
220  snprintf(port, sizeof(port) - 1, "/dev/%s", fname);
221  if (!file_exists(port))
222  continue;
223 
224  size_t len = strlen(port);
225  if (num_available_ports > 0)
226  len++;
227 
228  if (buffer_size > len)
229  {
230  /* append port to port_list */
231  if (num_available_ports)
232  strcat(port_list, ";");
233 
234  strcat(port_list, port);
235  buffer_size -= len;
236  }
237 
238  /* we found one more port */
239  num_available_ports++;
240  }
241  }
242 
243  closedir(dir_handle);
244  return num_available_ports;
245 }
246 #endif
247 
248 com_t* com_open(const char* port_name)
249 {
250  struct termios options;
251 
252  com_t* com_port = malloc(sizeof(com_t));
253  if(com_port == NULL)
254  return NULL;
255 
256  /*
257  * Open the serial port read/write, with no controlling terminal, and
258  * don't wait for a connection. See open(2) ("man 2 open") for details.
259  */
260  com_port->handle = open(port_name, O_RDWR | O_NOCTTY);
261 
262  if (com_port->handle == -1)
263  goto fail;
264 
265  /*
266  * Note that open() follows POSIX semantics: multiple open() calls to the
267  * same file will succeed unless the TIOCEXCL ioctl is issued. This will
268  * prevent additional opens except by root-owned processes.
269  * See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
270  */
271  if (ioctl(com_port->handle, TIOCEXCL) == -1)
272  {
273  /* Don't treat as fatal if the command is just not supported. */
274  if (errno != ENOTTY)
275  goto fail;
276  }
277 
278  /* Get the current options and save them so we can restore the default
279  * settings later.
280  */
281  if (tcgetattr(com_port->handle, &options) == -1)
282  {
283  goto fail;
284  }
285 
286  /*
287  * The serial port attributes such as timeouts and baud rate are set by
288  * modifying the termios structure and then calling tcsetattr to cause
289  * the changes to take effect. Note that the changes will not take effect
290  * without the tcsetattr() call. See tcsetattr(4) ("man 4 tcsetattr") for
291  * details.
292  *
293  * Set raw input (non-canonical) mode, with non-blocking reads.
294  * See tcsetattr(4) ("man 4 tcsetattr") and termios(4) ("man 4 termios")
295  * for details.
296  */
297  cfmakeraw(&options);
298  options.c_cc[VMIN] = 0;
299  options.c_cc[VTIME] = 0;
300 
301  /* Enable local mode, because the USBD_VCOM APP does not handle the
302  * virtual flow control lines
303  */
304  options.c_cflag |= CLOCAL;
305 
306  /* Cause the new options to take effect immediately. */
307  if (tcsetattr(com_port->handle, TCSANOW, &options) == -1)
308  goto fail;
309 
310  com_port->timeout_period_ms = 1000;
311  return com_port;
312 
313 fail:
314  free(com_port);
315  return NULL;
316 }
317 
318 void com_close(com_t* com_port)
319 {
320  /* close COM port */
321  close(com_port->handle);
322 
323  /* free allocated memory */
324  free(com_port);
325 }
326 
327 size_t com_send_data(com_t* com_port, const void* data, size_t num_bytes)
328 {
329  /* send data */
330  return write(com_port->handle, data, num_bytes);
331 
332 }
333 
334 size_t com_get_data(com_t* com_port,
335  void* data, size_t num_requested_bytes)
336 {
337  size_t num_received_bytes = 0;
338  char* read_buffer = (char*)data;
339  struct timespec time_of_last_byte;
340 
341  /* read data */
342  clock_gettime(CLOCK_MONOTONIC, &time_of_last_byte);
343  while (num_received_bytes < num_requested_bytes)
344  {
345  ssize_t num_bytes = read(com_port->handle,
346  read_buffer + num_received_bytes,
347  num_requested_bytes - num_received_bytes);
348  num_received_bytes += num_bytes;
349 
350  /* check for timeout */
351  struct timespec current_time;
352  clock_gettime(CLOCK_MONOTONIC, &current_time);
353  if (num_bytes != 0)
354  {
355  time_of_last_byte = current_time;
356  }
357  else
358  {
359  if ((current_time.tv_sec * 1000 + current_time.tv_nsec / 1000000) >
360  (time_of_last_byte.tv_sec * 1000 +
361  time_of_last_byte.tv_nsec / 1000000 +
362  com_port->timeout_period_ms))
363  {
364  break;
365  }
366  }
367  }
368  return num_received_bytes;
369 }
370 
371 void com_set_timeout(com_t* com_port, uint32_t timeout_period_ms)
372 {
373  com_port->timeout_period_ms = timeout_period_ms;
374 }
375 
376 /* --- Close open blocks -------------------------------------------------- */
377 
378 /* End of UNIX only code */
379 #endif /* (defined __APPLE__) || (defined LINUX) || (defined __linux__) */
380 
381 /* --- End of File -------------------------------------------------------- */
void com_set_timeout(com_t *com_port, uint32_t timeout_period_ms)
This function changes the timeout period of an open COM port.
size_t com_get_data(com_t *com_port, void *data, size_t num_requested_bytes)
This function reads data from an open COM port.
struct com_s com_t
Definition: COMPort.h:51
void com_close(com_t *com_port)
This function closes the specified COM port.
#define IFX_RADAR_VID
Definition: COMPort.h:45
This file defines the API to access a serial communication port.
size_t com_send_data(com_t *com_port, const void *data, size_t num_bytes)
This function sends data through an open COM port.
#define IFX_RADAR_FF_PID
Definition: COMPort.h:49
com_t * com_open(const char *port_name)
This functions opens the specified COM port.
#define IFX_RADAR_PID
Definition: COMPort.h:46
uint32_t com_get_port_list(char *port_list, size_t buffer_size)
This function returns a list of available COM ports.